<?php

date_default_timezone_set("Asia/Shanghai");

$CONFIG = [
	'app_id' => '您的app_id',
	'app_secret' => '您的app_secret',
];
$method = 'POST';
/**
 * 请求示例：淘口令解析
 */

$data = [
	'taoword' => '',//淘口令
	'accurate' => 0,//是否使用精准解析:（0.否；1.是）默认1；不使用精准解析可提升接口响应速度
	'method' => 'analyze.taoword'
];
$field['app_id'] = $CONFIG['app_id'];
$field['date'] = date('Y-m-d H:i:s');
$PostField = array_merge($field, $data);
sign_create($PostField, $CONFIG['app_secret']);//生成签名
$url = 'https://v3.api.haodanku.com/rest';
$header = array('content-type: application/json;charset=utf-8');
if ($method == 'GET') {
	$url .= '?' . createStrParam($PostField);
}
$result = curl($url, $method, $PostField, $header);

echo $result;


/**
 * curl 请求
 * @param $url -链接
 * @param string $method -请求方式
 * @param null $postFields -post数据
 * @param array $headers -
 * @return bool|string
 */
function curl($url, $method = "GET", $postFields = null, $headers = array())
{
	$ci = curl_init();
	curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	curl_setopt($ci, CURLOPT_FAILONERROR, false);
	curl_setopt($ci, CURLOPT_CONNECTTIMEOUT_MS, 5000);
	curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 5);
	curl_setopt($ci, CURLOPT_TIMEOUT, 5);
	curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
	curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
	curl_setopt($ci, CURLOPT_USERAGENT, "top-sdk-php");
	if ($method == 'POST') {
		curl_setopt($ci, CURLOPT_POST, true);
		if (!empty($postFields)) {
			$postFields = json_encode($postFields);
			curl_setopt($ci, CURLOPT_POSTFIELDS, $postFields);
		}
	}
	curl_setopt($ci, CURLOPT_URL, $url);
	curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ci, CURLINFO_HEADER_OUT, true);
	$response = curl_exec($ci);
	curl_close($ci);
	return $response;
}

/**
 * 生成签名
 * @param $data -请求数据组
 * @param string $secret -应用密钥
 */
function sign_create(&$data, $secret = '')
{
	ksort($data);
	$stringToBeSigned = '';
	foreach ($data as $k => $v) {
		if (!is_array($v) && "@" != substr($v, 0, 1)) {
			$stringToBeSigned .= "$k$v";
		}
	}
	$sign = strtoupper(md5($stringToBeSigned . $secret));
	$data['sign'] = $sign;
}

/**
 * 数据转url参数
 * @param $paramArr -请求数据组
 * @return string
 */
function createStrParam($paramArr)
{
	$strParam = '';
	foreach ($paramArr as $key => $val) {
		if ($key != '' && $val != '') {
			$strParam .= $key . '=' . urlencode($val) . '&';
		}
	}
	return trim($strParam, '&');
}